<template>
    <div>
        <div class="boxWrapper tabbox">
            <el-tabs v-model="currentName">
                <el-tab-pane label="数据库" name="1">
                        <span slot="label"><i class="iconfont">&#xe621;</i> 数据库</span>
                </el-tab-pane>
                <el-tab-pane label="数据字典" name="2">
                        <span slot="label"><i class="iconfont">&#xe657;</i> 数据字典</span>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div class="collection-management boxWrapper" v-if="currentName == '1'">
            <el-form :inline="true" size="small">
                <el-form-item label="流域">
                    <el-select v-model="basinId" placeholder="请选择" @change="handleChangeBasin" >
                    <el-option
                        v-for="item in basinSelect"
                        :key="item.id"
                        :label="item.basinName"
                        :value="item.id"
                        >
                    </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="电站">
                    <el-select v-model="stationId" placeholder="请选择" >
                    <el-option
                        v-for="item in stationSelect"
                        :key="item.id"
                        :label="item.stationName"
                        :value="item.id"
                        >
                    </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据库类型">
                    <el-select v-model="dbType" placeholder="请选择" clearable>
                        <el-option
                        v-for="item in dataBaseList"
                        :key="item"
                        :label="item"
                        :value="item"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>  
                <el-form-item>
                    <el-button type="primary" @click="handleGetDBlist" icon="el-icon-search" size='small'>查询</el-button>
                    <el-button type="primary" @click="handleAddData()" icon="el-icon-plus" size='small' >添加数据库</el-button>
                </el-form-item>  
            </el-form>
            <div class="list-box1">
                <el-table :data="tableList" height="calc(100vh - 270px)" border>
                <el-table-column prop="stationName" label="电站" align="center"></el-table-column>
                <el-table-column prop="alias" label="别名" align="center"></el-table-column>
                <el-table-column prop="dbType" label="数据库类型" align="center"></el-table-column>
                <el-table-column prop="dbName" label="数据库名称" align="center"></el-table-column>
                <el-table-column prop="dbHost" label="主机地址" align="center"></el-table-column>
                <el-table-column prop="dbPort" label="端口" align="center"></el-table-column>
                <el-table-column prop="dictName" label="模式+字典" align="center" width="220">
                <template slot-scope="scope">
                    <div v-for="(item,index) in scope.row.dbSchemas" :key="index">
                    {{item.schemaName}}:{{item.dictName}}({{item.dictVersionName}})
                    </div>
                </template>
                </el-table-column>
                <el-table-column prop="startTime" label="创建时间" align="center"></el-table-column>        
                <el-table-column label="操作" align="center" width="220">
                <template slot-scope="scope">
                    <el-link type="primary" icon="el-icon-edit" @click="handleAddData(scope.row)" :underline="false">编辑</el-link>
                    <el-link type="danger" icon="el-icon-delete" @click="handleDelList(scope.row)" :underline="false" style="margin-left: 10px;">删除</el-link>
                </template>
                </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="collection-management boxWrapper" v-if="currentName == '2'">
            <dictonary></dictonary>
        </div>
        


        <el-dialog 
            :title="`${editDataList ? '编辑' : '新增'}数据库配置`" 
            :visible.sync="dialogVisible" 
            width="1100px" 
            :before-close="handleCloseBasinDialog" 
            v-dialogDrag
        >
    <div class="dialog-content">
      <el-form 
        ref="basinForm" 
        :model="basinForm" 
        label-width="100px" 
        size="medium" 
        class="database-form"
      >
        <!-- 基础信息区域 -->
        <div class="form-section">
          <div class="section-title">基础信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="流域" prop="basinId">
                <el-select 
                  v-model="basinForm.basinId" 
                  placeholder="选择流域" 
                  @change="handleChangeBasinDialog"
                  class="form-input"
                >
                  <el-option
                    v-for="item in basinSelect"
                    :key="item.id"
                    :label="item.basinName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电站" prop="stationId">
                <el-select 
                  v-model="basinForm.stationId" 
                  placeholder="选择电站" 
                  class="form-input"
                >
                  <el-option
                    v-for="item in stationSelectDialog"
                    :key="item.id"
                    :label="item.stationName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据库类型" prop="dbType">
                <el-select 
                  v-model="basinForm.dbType" 
                  placeholder="选择数据库类型" 
                  class="form-input"
                >
                  <el-option
                    v-for="item in dataBaseList"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="别名(备注)" prop="alias">
                <el-input 
                  v-model="basinForm.alias" 
                  placeholder="请输入别名" 
                  class="form-input"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 连接信息区域 -->
        <div class="form-section">
          <div class="section-title">连接信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据库名称" prop="dbName">
                <el-input 
                  v-model="basinForm.dbName" 
                  placeholder="请输入数据库名称" 
                  class="form-input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主机地址" prop="dbHost">
                <el-input 
                  v-model="basinForm.dbHost" 
                  placeholder="请输入主机地址" 
                  class="form-input"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="端口" prop="dbPort">
                <el-input 
                  v-model="basinForm.dbPort" 
                  placeholder="请输入端口" 
                  class="form-input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input 
                  v-model="basinForm.username" 
                  placeholder="请输入用户名" 
                  class="form-input"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="密码" prop="password">
            <el-input 
              v-model="basinForm.password" 
              placeholder="请输入密码" 
              show-password 
            />
          </el-form-item>
        </div>

        <!-- 数据库模式设置 -->
        <div class="form-section">
          <div class="section-title">
            数据库模式设置
            <el-tooltip 
              effect="dark" 
              content="如果数据库不支持模式或仅有一个模式，模式名为空即可；如果数据库存在多个模式，则添加多个模式" 
              placement="top"
            >
              <i class="el-icon-info info-icon"></i>
            </el-tooltip>
          </div>
          
          <div class="schema-list">
            <div 
              v-for="(item, index) in basinForm.dbSchemas" 
              :key="index" 
              class="schema-item"
            >
              <el-row :gutter="15">
                <el-col :span="8">
                  <el-form-item :label="`模式${index + 1}`" class="no-margin">
                    <el-input 
                      v-model="item.schemaName" 
                      placeholder="模式名(schema)" 
                      size="small"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="数据字典" class="no-margin">
                    <el-select 
                      v-model="item.dictId" 
                      placeholder="选择数据字典" 
                      size="small"
                      @change="handleChangeDict($event, index)"
                    >
                      <el-option
                        v-for="dict in dictSelect"
                        :key="dict.id"
                        :label="dict.name"
                        :value="dict.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="字典版本" class="no-margin">
                    <el-select 
                      v-model="item.dictVersionName" 
                      placeholder="选择版本" 
                      size="small"
                      @change="handleChangeVersionName($event, index)"
                      @focus="handleVersionFocus(index)"
                    >
                      <el-option
                        v-for="version in dictVersionSelect"
                        :key="version.id"
                        :label="version.versionName"
                        :value="version.versionName"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="1">
                  <el-tooltip effect="dark" content="删除模式" placement="top">
                    <el-button 
                      icon="el-icon-delete" 
                      size="small" 
                      type="danger" 
                      @click="handleDelModel(index)"
                      class="delete-btn"
                    />
                  </el-tooltip>
                </el-col>
              </el-row>
            </div>
          </div>

          <el-button 
            type="primary" 
            icon="el-icon-plus" 
            @click="handleAddModel" 
            size="small"
            class="add-schema-btn"
          >
            添加模式
          </el-button>
        </div>
      </el-form>
    </div>

    <div class="dialog-footer">
      <el-button @click="handleCloseBasinDialog" size="small" icon="el-icon-close" class="cancel-btn">取消</el-button>
      <el-button 
        type="success" 
        @click="handleTestData" 
        icon="el-icon-connection" 
        size="small"
        class="confirm-btn"
      >
        测试连接
      </el-button>
      <el-button 
        type="primary" 
        @click="handleSaveDbData" 
        icon="el-icon-check" 
        size="small"
        class="confirm-btn"
      >
        保存配置
      </el-button>
    </div>
  </el-dialog>
    </div>
</template>
<script>
import bus from '@/utils/eventBus.js';
import {GetAllBasin,GetStationByBasinID,DBlist,dbConfig,DictListDetail,DictList,DictVersionList,connectTest,DBlistEdit,DBlistAdd,DaStationDel } from '@/api/https'
import dictonary from '@/components/page/collect/dictonary.vue'
import { encrypt, decrypt} from '@/utils/sm4.js';
export default ({
    name:'database',
    components:{dictonary},
    data() {
        return{
            currentName:'1',
            basinSelect:[],
            stationSelect:[],
            stationId:'',
            basinId:'',
            dataBaseList:[],
            dbType:'',
            tableList:[],
            dbTypeList:[],
            editDataList:false,
            basinForm:{},
            dialogVisible:false,
            stationSelectDialog:[],
            dictSelect:[],
            dictVersionSelect:[],
        }
    },
    mounted(){
        bus.$emit('showBasin', false);
        this.getAllBasin()
        this.getConfig()
        this.getDictListData()
    },
    activated(){
        bus.$emit('showBasin', false);
    },
    methods:{
       getAllBasin(){
            GetAllBasin({
                ORGID:0,
            }).then(res=>{
                if(res.isSuccess){
                    this.basinSelect = res.data
                    this.basinId = res.data[0].id
                    this.getStationSelect()
                }
            })
        },
        getStationSelect(){
            GetStationByBasinID(this.basinId).then(res=>{
                if(res.isSuccess){
                this.stationSelect = res.data
                this.stationId = res.data[0].id
                this.handleGetDBlist()
                }
            })
        },
        getConfig(){
          dbConfig().then(res=>{
            if(res.code == 200){
              this.dataBaseList = res.data.dbType
              this.dbTypeList = res.data.dbDataType
            }
          })
        },
        handleGetDBlist(){
          DBlist({
            basinId:this.basinId,
            stationId:this.stationId,
            dbType:this.dbType,
            page:1,
            size:500
          }).then(res=>{
            if(res.code == 200){
              this.tableList = res.data.list
            }
          })
        },
        handleAddData(data){
            if(data){
                this.editDataList = true
                DictListDetail({
                  dbId:data.id
                }).then(res=>{
                  if(res.code == 200){
                    const {id,basinId,stationId,dbType,alias,dbName,dbHost,dbPort,username,password,dbSchemas} = res.data
                    const list = []
                    dbSchemas.forEach(item => {
                      list.push({
                        schemaId:item.schemaId,
                        schemaName:item.schemaName,
                        dictVersionName:item.dictVersionName,
                        dictId:item.dictId,
                        dictVersionId:item.dictVersionId
                      })
                    });
                    const _data = {
                      id:id,
                      basinId:Number(basinId),
                      stationId:Number(stationId),
                      dbType:dbType,
                      alias:alias,
                      dbName:dbName,
                      dbHost:dbHost,
                      dbPort:dbPort,
                      username:username,
                      password:decrypt(password),
                      dbSchemas:list
                    }
                    this.basinForm ={..._data}
                    this.getStationSelectDialog()
                  }
                })
            }else{
              this.editDataList = false
              this.basinForm = {
                dbSchemas:[{
                  schemaName:'',
                  dictId:'',
                  dictVersionId:'',
                  dictVersionName:''
                }]
              }
            }
            this.dialogVisible = true
        },
        handleCloseBasinDialog(){
            this.dialogVisible = false
            this.basinForm = {}
            this.editDataList = false
        },
        handleTestData(){
            const loading = this.$loading({
                lock: true,
                text: '连接测试中，请稍后',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            const {dbHost,dbName,dbPort,dbType,password,stationId,username} = this.basinForm
            const _password = encrypt(password)
            connectTest({
                stationId:stationId,
                dbType:dbType,
                dbName:dbName,
                dbHost:dbHost,
                dbPort:dbPort,
                username:username,
                password:_password
            }).then(res=>{
                loading.close();
                if(res.code == 200){
                    this.$message.success('连接成功！可保存当前配置')
                }else{
                    this.$message.error(res.msg)
                }
            })
        },
        handleSaveDbData(){
            if(this.editDataList){
                const data = {...this.basinForm}
                data.password = encrypt(this.basinForm.password)
                DBlistEdit(data).then(res=>{
                    if(res.code == 200){
                        this.handleGetDBlist()
                        this.handleCloseBasinDialog()
                    }else{
                        this.$message.error(res.msg)
                    }
                })
            }else{
                const data = {...this.basinForm}
                data.password = encrypt(this.basinForm.password)
                DBlistAdd(data).then(res=>{
                    if(res.code == 200){
                        this.handleGetDBlist()
                        this.handleCloseBasinDialog()
                    }else{
                        this.$message.error(res.msg)
                    }
                })
            }
        },
        handleChangeBasinDialog(val){
            const _d = {...this.basinForm}
            _d.basinId = val
            _d.stationId = ''
            this.basinForm = {..._d}
            this.getStationSelectDialog()
        },
        getStationSelectDialog(){
            GetStationByBasinID(this.basinForm.basinId).then(res=>{
                if(res.isSuccess){
                    this.stationSelectDialog = res.data || []
                }
            })
        }, 
        handleAddModel(){
          this.basinForm.dbSchemas.push({
            schemaName:'',
            dictId:'',
            dictVersionId:'',
            dictVersionName:''
          })
        },
        handleDelModel(index){
          this.basinForm.dbSchemas.splice(index,1)
        },
        handleChangeBasin(val){
          this.basinId = val
          this.getStationSelect()
        },
        getDictListData(){
          DictList({
            page:1,
            size:500,
            keyword:''
          }).then(res=>{
            if(res.code == 200){
              this.dictSelect = res.data.list
            }
          })
        },
        handleVersionFocus(index){
          if(this.basinForm.dbSchemas[index].dictId){
            DictVersionList({
              page:1,
              size:500,
              isRelease:1,
              id:this.basinForm.dbSchemas[index].dictId
            }).then(res=>{
              if(res.code == 200){
                this.dictVersionSelect = res.data.list
              }
            })
          }else{
            this.dictVersionSelect = []
          }
        },
        handleChangeDict(val,index){
          const data = [...this.basinForm.dbSchemas]
          data[index].dictId = val
          data[index].dictVersionId = ''
          data[index].dictVersionName = ''
          this.basinForm.dbSchemas[index] = data[index]
        },
        handleChangeVersionName(val,index){
          const data = [...this.basinForm.dbSchemas]
          data[index].dictVersionName = val
          this.dictVersionSelect.forEach(item=>{
            if(item.versionName == val){
              data[index].dictVersionId = item.id.toString()
            }
          })
          this.basinForm.dbSchemas[index] = data[index]
        },
        handleDelList(data){
          this.$confirm(`是否确认删除该数据库，删除后不可恢复！`,'提示',{
            type:'warning'
          }).then(() => {
            DaStationDel({
              dbId:data.id
            }).then(res=>{
              if(res.code == 200){
                this.handleGetDBlist()
              }else{
                this.$message.error(res.msg)
              }
            })
          }).catch(() => {});  
        },
    }
})
</script>
<style scoped lang="scss">
.collection-management{
    padding:20px;
    box-sizing: border-box;
    margin-top:10px;
}


.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 10px 0;
}

.database-form {
  padding: 0 10px;
}

.form-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-icon {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
}

.form-input {
  width: 100%;
}

.schema-list {
  margin-bottom: 15px;
}

.schema-item {
  padding: 12px;
  background: white;
  border: 1px solid #e6ebf5;
  border-radius: 4px;
  margin-bottom: 10px;
  ::v-deep .el-form-item{
    margin-bottom: 0px;
  }
}
.delete-btn{
    padding:5px !important;
    margin-top:4px;
}




.add-schema-btn {
  width: 100%;
}

</style>
